package com.hand.wfive.activity.picker

import android.graphics.Color
import android.util.Log
import com.qmuiteam.qmui.widget.QMUITopBarLayout
import com.rxjava.rxlife.RxLife
import com.hand.wfive.R
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.entity.BaseModel
import com.hand.wfive.entity.FileEvent
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.FileUpdateEvent
import com.hand.wfive.entity.FileWord2ImagesModel
import com.hand.wfive.entity.Params
import com.hand.wfive.entity.WordFileCountModel
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.ui.VipActivity
import com.hand.wfive.loginAndVip.ui.VipCenterActivity
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import com.hand.wfive.view.MsgDialog
import com.hand.wfive.view.MsgDialog2
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import okhttp3.internal.wait
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.doAsyncResult
import org.jetbrains.anko.findOptional
import rxhttp.retry
import rxhttp.toClass
import rxhttp.toOkResponse
import rxhttp.wrapper.param.RxHttp
import java.util.concurrent.TimeUnit

abstract class BasePreviewActivity : BaseActivity() {

    protected lateinit var mPath: String
    protected lateinit var mFileModel: FileModel

    override fun init() {
        mPath = intent.getStringExtra(Params.path) ?: ""
        if (mPath.isEmpty()) {
            finish()
            return
        }

        val topBar = findOptional<QMUITopBarLayout>(R.id.topBar)
        if (topBar != null) {
            topBar.addLeftBackImageButton().singleClick { finish() }
            topBar.addRightTextButton("上传", R.id.top_bar_right_text)
                .singleClick { onUploadFile() }
            topBar.updateBottomSeparatorColor(Color.parseColor("#CCCCCC"))
        }

        onPreviewFile()

        mFileModel = FileModel()
        mFileModel.status = Params.fileStatusUnsign
        mFileModel.filePath = mPath
        mFileModel.fileName = mPath.substring(mPath.lastIndexOf("/") + 1)
        mFileModel.type = getUploadFileType()
        mFileModel.size = FileUtils.getFileSize(mPath)
    }

    protected abstract fun onPreviewFile()

    protected abstract fun getUploadFileType(): String

    protected open fun onUploadFile() {
        uploadFile()

    }

    protected fun uploadFile() {
        if (mFileModel.type == Params.pickerWord) {
            RxHttp.postForm(ApiConfig.getUserUploadWordCount)
                .add("userId", UserManager.getInstance().userId)
                .add("appid", LoginConfig.AppId)
                .asClass(WordFileCountModel::class.java)
                .to(RxLife.toMain(this))
                .subscribe({
                    if (it.code == 200) {
                        if (!UserManager.getInstance().isVip && it.`object` > 0) {
                            dismissTip()
                            MsgDialog2(
                                mContext,
                                "上传提醒",
                                "非会员用户只可上传一次word文件，请开通会员后再试！\n（仅限Word上传）",
                                negativeBg = R.drawable.btn_dialog_msg_positive_left,
                                positiveBg = R.drawable.btn_dialog_msg_negative_right,
                                negativeText = "确定",
                                positiveText = "取消",
                            ) { position ->
                                if (position == 0) {
                                    VipCenterActivity.show(mContext)
                                }
                            }.show()
                        }else{
                            relToUploadFile()
                        }
                    } else {
                        dismissTip()
                        if (UserManager.getInstance().isVip) {
                            MsgDialog2(
                                mContext,
                                "上传提醒",
                                "上传Word文件本月已达上限，请购买单独资源包后再试！",
                                negativeBg = R.drawable.btn_dialog_msg_positive_left,
                                positiveBg = R.drawable.btn_dialog_msg_negative_right,
                                negativeText = "确定",
                                positiveText = "取消",
                            ) { position ->
                                if (position == 0) {
                                    VipCenterActivity.show(mContext)
                                }

                            }.show()

                        } else {
                            MsgDialog2(
                                mContext,
                                "上传提醒",
                                "非会员用户只可上传一次word文件，请开通会员后再试！\n（仅限Word上传）",
                                negativeBg = R.drawable.btn_dialog_msg_positive_left,
                                positiveBg = R.drawable.btn_dialog_msg_negative_right,
                                negativeText = "确定",
                                positiveText = "取消",
                            ) { position ->
                                if (position == 0) {
                                    VipCenterActivity.show(mContext)
                                }
                            }.show()
                        }
                    }
                }, {
                    showNormalTip("上传失败")
                    onUploadFileFailure()
                })
        } else {
            dismissTip()
            relToUploadFile()
        }
    }

    private fun relToUploadFile() {
        dismissTip()
        showLoadingProgress()
        mFileModel.fileId = "${UserManager.getInstance().userId}/file/${
            System.currentTimeMillis()
        }_${mFileModel.fileName.replace(",", "")}"

        OssRequest.getInstance().uploadFile(mFileModel, object : OssCallBack {
            override fun onSuccess() {
                if (mFileModel.type == Params.pickerWord) {
                    word2Images()
                } else {
                    dismissTip()
                    EventBus.getDefault()
                        .post(FileEvent(Params.fileTypeAll, Params.fileStatusUnsign))
                    setResult(RESULT_OK)
                    finish()
                }


            }

            override fun onFailure(msg: String) {
                showNormalTip(msg.ifEmpty { "上传失败" })
                onUploadFileFailure()
            }
        })
    }

    protected fun word2Images() {
        //OssRequest.getInstance().getFileUrl(mFileModel.fileId)
        RxHttp.postForm(ApiConfig.word2images)
            .add("userId", UserManager.getInstance().userId)
            .add("wordPath", OssRequest.getInstance().getFileUrl(mFileModel.fileId))
            .add("wordFileName", mFileModel.fileName)
            .add("fileId", mFileModel.fileId)
            .add("appid", LoginConfig.AppId)
            .asClass(FileWord2ImagesModel::class.java)
            .to(RxLife.toMain(this))
            .subscribe({
                createImageFinish(it.data)
            }, {
                showNormalTip("上传失败")
                onUploadFileFailure()
            })

    }

    var taskObservable: Disposable? = null
    var taskCount = 0
    fun createImageFinish(taskId: String) {
        val taskOb = RxHttp.postForm(ApiConfig.wordIsCreateImage)
            .add("userId", UserManager.getInstance().userId)
            .add("wordPath", OssRequest.getInstance().getFileUrl(mFileModel.fileId))
            .add("wordFileName", mFileModel.fileName)
            .add("fileId", mFileModel.fileId)
            .add("appid", LoginConfig.AppId)
            .add("taskId", taskId)
            .asClass(FileWord2ImagesModel::class.java)
        taskObservable = Observable.interval(3, TimeUnit.SECONDS)
            .flatMap {
                taskOb
            }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({

                taskCount++
                if (it.code == 200) {
                    dismissTip()
                    if (!taskObservable!!.isDisposed) {
                        taskObservable!!.dispose()
                        EventBus.getDefault()
                            .post(FileEvent(Params.fileTypeAll, Params.fileStatusUnsign))
                        setResult(RESULT_OK)
                        finish()
                    }
                } else {
                    if (taskCount > 3) {
                        showErrorTip("上传失败")
                        taskCount = 0
                        if (!taskObservable!!.isDisposed) {
                            taskObservable!!.dispose()

                        }
                    }
                }

            }, {
                showNormalTip("上传失败")
                onUploadFileFailure()
            })


    }

    protected open fun onUploadFileFailure() {

    }
}